package com.zh.oauth.controller;


import com.alibaba.fastjson.JSON;
import com.zh.common.constans.AuthConstant;
import com.zh.common.util.OkHttpClientUtil;
import com.zh.oauth.entity.ElecUser;
import io.swagger.annotations.Api;
import okhttp3.Response;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

@Api(value = "付惠吧鉴权控制器", produces = "application/json", tags = {"付惠吧鉴权控制器"})
@RestController
@RequestMapping("/fhb")
public class FuHuiBaLoginController {

    @PostMapping("/getToken")
    @ResponseBody
    public Map<String,Object> login(@RequestBody ElecUser user, HttpServletRequest req, HttpServletResponse res) throws Exception {
        Map<String,Object> result = new HashMap<>();
        // 验证用户信息
        res.setContentType("text/html;charset=utf-8");
        res.setCharacterEncoding("utf-8");
        // 设置请求体
        Map<String, String> bodyMap = new HashMap<>();
        bodyMap.put("scope", user.getScope());
        bodyMap.put("grant_type", user.getGrantType());
        // 设置请求头
        Map<String, String> headMap = new HashMap<>();
        headMap.put("Content-Type", "application/x-www-form-urlencoded");
        headMap.put("Authorization", req.getHeader("Authorization"));
        // 通过 HTTP 客户端请求登录接口
        Response response = OkHttpClientUtil.getInstance().postData(AuthConstant.URL_OAUTH_TOKEN, bodyMap, headMap);
        if (!response.isSuccessful()) {
            result.put("Code", response.code());
            result.put("Message","请检查授权码是否正确");
            return result;
        }
        String jsonString = Objects.requireNonNull(response.body()).string();
        HashMap jsonMap = JSON.parseObject(jsonString, HashMap.class);
        result.put("Code", 100);
        result.put("Message", "操作完成");
        result.put("Data", jsonMap);
        return result;
    }
}
